﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using System.IO;
using System.Drawing;
using System.Threading;
using Google.Protobuf.WellKnownTypes;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Math;


namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// 外协完工_完工到ERP
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CRM_WXMoSTtoERPController : ControllerBase
    {
        private readonly ILogger _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;
        public readonly string gz_con;


        public CRM_WXMoSTtoERPController(ILogger<CRM_WXMoSTtoERPRequestDto> logger, IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration, ILoggerFactory loggerFactory)
        {
            _WMSTokenCheckService = wmsTokenCheckService;
            con = _configuration.GetConnectionString("DDM_DbConnection_ZH");
            gz_con = _configuration.GetConnectionString("GZ_WMS_DbConnection");
            _logger = loggerFactory.CreateLogger<CRM_WXMoSTtoERPController>();

        }

        /// <summary>
        /// 外协完工_完工到ERP
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostMoStIntoERP([FromBody] CRM_WXMoSTtoERPRequestDto strparm)
        {
            string  strMsg = "";
            object log = "";
            log = strparm;
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            CRM_WXMoSTtoERPResponseDto re = new CRM_WXMoSTtoERPResponseDto();
            ERP_CompleteTOERPRequestDto input = new ERP_CompleteTOERPRequestDto();
            List<ERP_CompleteTOERP_DataRequestDto> details = new List<ERP_CompleteTOERP_DataRequestDto>();


            if (strparm.erp_moorder == "")
            {
                
                strMsg = "erp_moorder不能为空，完工失败！";
            }
            if (strparm.data ==null)
            {

                strMsg = "条码明细不能为空！";
            }


            Dictionary<string, string> dic = new Dictionary<string, string>(); //查询公用dic
            try
            {
                if (strMsg == "")
                {
                    // 检查并获取重复条码
                    var duplicates = strparm.data
                        .GroupBy(item => item.barcode_no)
                        .Where(g => g.Count() > 1)
                        .ToList();

                    if (duplicates.Any())
                    {
                        foreach (var group in duplicates)
                        {
                            // 如果需要列出重复项的详细信息
                            foreach (var item in group)
                            {
                                strMsg += $"条码号={item.barcode_no},数据重复，请确认后再试！ \n";
                            }
                        }
                    }


                    //foreach (var row in strparm.data)
                    //{
                    //    //没报错才执行逻辑
                    //    if (strMsg=="")
                    //    {
                    //        dic = new Dictionary<string, string>(); //查询托盘是否存在历史记录
                    //        dic.Add("parent_barcode_no", row.parent_barcode_no);
                    //        DataTable pa_dt = MethodHelp.GetTableInfo("TMS0199", dic, con);
                    //        if (pa_dt.Rows.Count>0)
                    //        {
                    //            strMsg = strMsg+ "-箱号=<" + row.parent_barcode_no+">存在于单据号=<"+ pa_dt.Rows[0]["mo_ordercode"].ToString() + ">上已完工数据，请确认后再试！";
                    //        }
                    //        else
                    //        {
                    //            dic = new Dictionary<string, string>(); //查询条码是否存在历史记录
                    //            dic.Add("barcode_no", row.barcode_no);
                    //            DataTable bac_dt = MethodHelp.GetTableInfo("TMS0200", dic, con);
                    //            if (bac_dt.Rows.Count>0)
                    //            {
                    //                strMsg = strMsg + "-组件条码=<" + row.barcode_no + ">存在于单据号=<" + bac_dt.Rows[0]["mo_ordercode"].ToString() + ">上已完工数据，请确认后再试！";
                    //            }
                    //        }
                    //    }
                    //}

                    if (strMsg=="")
                    {
                        string transaction_date = DB.ToDateTime(strparm.transaction_date).AddMinutes(-5).ToString("yyyy-MM-dd HH:mm:ss");

                        details.Add(new ERP_CompleteTOERP_DataRequestDto
                        {
                            ORGANIZATION_CODE = strparm.factory_code,
                            WIP_ENTITY_NAME = strparm.erp_moorder,
                            TRANSACTION_TYPE = strparm.transaction_type,
                            PRIMARY_ITEM_NUMBER = strparm.material_code,
                            RANK = strparm.material_grade,
                            TRANSACTION_DATE = transaction_date,
                            SUBINVENTORY_CODE = strparm.warehouse_code,
                            LOCATOR = strparm.location_code,
                            COMPLETE_ITEM_NUMBER = strparm.material_code,
                            LOT_NUMBER = strparm.batch_no,
                            COMPLETE_QTY = strparm.material_amount.ToString(),
                            LINE_ATTRIBUTE3 = null,
                            PRIMARY_UOM_CODE = strparm.material_unit,
                            USER_NAME = strparm.user_no,
                            OVERCOMPLETION = "Y",
                            SOURCE_NUM = strparm.crm_moid
                        });

                        if (details.Count > 0)
                        {
                            input.PV_SOURCE_SYS_CODE = "CRM";
                            input.PV_BUSINESS_TYPE_CODE = "CRM_COMPLETE";
                            input.PV_SYNCHRO_FLAG = "Y";
                            input.ROWS = details;

                            Dictionary<string, string> urldic = new Dictionary<string, string>(); //URL获取dic
                            urldic.Add("function_description", "内部:ERP工单完工");//查看URL配置表地址描述
                            DataTable url_dt = MethodHelp.GetTableInfo("TMS0004", urldic, con);//获取URL地址
                            if (url_dt.Rows.Count > 0)
                            {
                                string jsonText = JsonConvert.SerializeObject(input);
                                var reAgv = DB.httpPost(url_dt.Rows[0]["interface_url"].ToString(), jsonText, "", "否");
                                ERP_PickTOERPResponseDto psp = JsonConvert.DeserializeObject<ERP_PickTOERPResponseDto>(reAgv);
                                if (psp.statusCode > 0)
                                {
                                    strMsg = "ERP返回错误:" + psp.message;
                                }
                            }
                        }
                    }                   
                }               
            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }
            if (strMsg=="")
            {
                re.code = 0;
                re.message = "";
            }
            else
            {
                re.code = 500;
                re.message = strMsg;
            }

            _logger.LogInformation(JsonConvert.SerializeObject(re));
            return new JsonResult(re);
        }

      
    }
}
